package com.henghe.frame.auth.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * Description:
 * Author: LiuWenQing
 * Datetime: 2023/3/18 09:17
 */
@Component
@Slf4j
public class TokenUtil {

    @Autowired(required = false)
    HttpServletRequest request;
    @Autowired
    TokenService tokenService;

    public final String ADMIN_NAME = "admin";

    /**
     * 从request的token中获取用户ID
     *
     * @return
     */
    public Long getUserId() {
        try {
            String data = (String) request.getAttribute("pdata");
            if (!"-1".equals("data")) {
                Object userId = JSON.parseObject(data).get("userId");
                if(Objects.nonNull(userId)){
                    return Long.parseLong(userId.toString().replace("\"",""));
                }else{
                    return null;
                }
            }
        } catch (Exception e) {
            return null;
        }
        return null;
    }

    /**
     * 从request的token中获取用户名
     *
     * @return
     */
    public String getUserName() {
        try {
            String data = (String) request.getAttribute("pdata");
            if (!"-1".equals("data")) {
                return JSON.parseObject(data).getString("userName").replaceAll("\"","");
            }
        } catch (Exception e) {
            return null;
        }
        return null;
    }

    public Boolean isAdmin(){
        return getUserName().equals(ADMIN_NAME);
    }

    public JSONObject getTokenData() {
        try {
            String data = (String) request.getAttribute("pdata");
            if (!"-1".equals("data")) {
                return JSON.parseObject(data);
            }
        } catch (Exception e) {
            return null;
        }
        return null;
    }
}
